#! /bin/bash
#
# boxio		init for BoxIo server
#

### BEGIN INIT INFO
# Provides:          boxio
# Required-Start:    $all
# Required-Stop:     $all
# Should-Start:
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Server IOBL BoxIo
# Description:       Server InOneByLegrand LAMP for USBCPL 88213
### END INIT INFO

set -e

if [ -r "/lib/lsb/init-functions" ]; then
  . /lib/lsb/init-functions
else
  echo "E: /lib/lsb/init-functions not found, lsb-base (>= 3.0-6) requiere"
  exit 1
fi

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/boxio
NAME=boxio
DESC="Server BoxIo"
PIDFILE=/var/run/$NAME.pid
LOGFILE=/var/log/$NAME.log
ERRORFILE=/var/log/$NAME.err

test -f $DAEMON || exit 0

# Defaults
#CONFFILE="/etc/boxio.conf"
SERVERPATH="/var/www/back/server.php"
CONTROLPORT="2000"

# Read file conf not implanted
#[ -r /etc/default/boxio ] && . /etc/default/boxio

start () {
  if ! pidofproc -p "$PIDFILE" >/dev/null; then
    service ser2net restart
    sleep 5
    log_daemon_msg "Starting $DESC" "$NAME"
    start_daemon -p $PIDFILE $DAEMON $SERVERPATH -l $LOGFILE -b $ERRORFILE &
    pidof $NAME > $PIDFILE
    ret=$?
    log_end_msg 0
  else
    log_daemon_msg "Starting $DESC" "$NAME"
    log_failure_msg "already running!\n"
    log_end_msg 1
    exit 1
  fi
  return $ret
}

stop () {
  log_daemon_msg "Stopping $DESC" "$NAME"
  killproc -p "$PIDFILE" "$DAEMON" "$SIG" &>/dev/null
  if ! pidofproc -p "$PIDFILE" >/dev/null; then
    rm -f $PIDFILE
  fi
  log_end_msg 0
  service ser2net stop
}

status ()
{
  log_action_begin_msg "checking $DESC"
  if pidofproc -p "$PIDFILE" >/dev/null; then
    log_action_end_msg 0 "$NAME running"
  else
    if [ -e "$PIDFILE" ]; then
      log_action_end_msg 1 "$NAME error"
      exit 1
    else
      log_action_end_msg 0 "$NAME stopped"
      exit 3
    fi
  fi
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	sleep 5
	start
	log_daemon_msg "Restarting $DESC" "$NAME"
	log_end_msg 0
	;;
  status)
  	status
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|status}" >&2
	exit 1
	;;
esac

exit 0
